<?php
/**
 * Create by Phpstorm
 * User: Peco
 * Date: 2019/11/20
 * Time: 11:28
 * BannerRepository.php
 */

namespace App\Repositories;

use App\Models\Banner;

class BannerRepository extends BaseRepositories
{
    /**
     * @var Banner 注入的数据模型
     */
    protected  $banner;

    /**
     * 引入attachment操作
     * @var AttachmentRepository
     */
    protected $attachmentRepository;

    /**
     * BannerRepository constructor.
     * @param Banner $banner
     * @param AttachmentRepository $attachmentRepository
     */
    public function __construct(Banner $banner,
                                AttachmentRepository $attachmentRepository)
    {
        $this->banner = $banner;
        $this->attachmentRepository = $attachmentRepository;
    }

    /**
     * @param array $data
     * @param int $limit
     * @return mixed
     */
    public function getBannerPageRepository(array $data, $limit = LIMIT_PAGE){
        return $this->banner
            ->where($data)
            ->orderBy('sort', 'asc')
            ->paginate($limit);
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function addBannerRepository(array $data){
        $id = $this->banner->insertGetId($data);

        //关联attachment
        $this->attachmentRepository->bindBelongs($id, MODEL_BANNER, $data['image']);

        return $this->banner;
    }

    /**
     * @param array $data
     * @param int $id
     * @return mixed
     */
    public function editBannerRepository(array $data, int $id){
        if($data['imageAttachment']){
            //关联attachment
            $this->attachmentRepository->bindBelongs($id, MODEL_BANNER, $data['imageAttachment']);
        }
        return $this->banner->where('id', $id)->update($data['data']);
    }

    /**
     * 更新banner状态
     * @param array $data
     * @return mixed
     */
    public function updateStatusRepository(array $data){
        return $this->banner->where('id', $data['id'])->update(['status'=>$data['status']]);
    }

    /**
     * @param int $id
     * @return mixed
     */
    public function deleteBannerRepository(int $id){
        return $this->banner->where('id', $id)->delete();
    }

    /**
     * @param int $id
     * @return mixed
     */
    public function getBannerDetailRepository(int $id){
        return $this->banner->findOrFail($id);
    }
}
